package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Aspect
@Component
public class GuiGuLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..))&&@annotation(guiGuLogin)")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp,GuiGuLogin guiGuLogin) throws Throwable {
        Object resultObject = new Object();
        log.info("前置通知...");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");

        String key =RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        UserInfoVo userInfoVo = (UserInfoVo)redisTemplate.opsForValue().get(key);

        if (guiGuLogin.required() && userInfoVo ==null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        if (userInfoVo !=null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
        }

        resultObject = pjp.proceed();

        AuthContextHolder.removeUserId();
        log.info("后置通知...");

        return resultObject;
    }
}
